<!-- 试验构建_包括全局因素配置、想定级因素配置、模型级因素配置 -->
<template>
    <div class="experiment-build-container">
        <div class="experiment-build-container-top">

            <div class="experiment-build-container-top_item" @click="$router.go(-1)">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.experimentDesign.return") }}</div>
            </div>

        </div>

        <div class="experiment-build-container-bottom">
            <!-- 左侧结构 -->
            <div class="e-b-left flex flex-col">
                <div class="w-full flex items-center" style="gap: 4px">
                    <el-input class="jtyj-input" prefix-icon="el-icon-search" v-model="queryContent"
                        @input="handleQueryContent" clearable></el-input>
                    <el-button class="jtyj-btn-s" type="info" style="width: 32px; height: 32px">
                        <span role="img" class="appIcon">
                            <svg-icon icon-class="delete" width="16" height="16" />
                        </span>
                    </el-button>
                    <el-button class="jtyj-btn-s" type="primary" @click="handleAddScenario" style="width: 32px; height: 32px">
                        <span role="img" class="appIcon">
                            <svg-icon class="jtyj-primary-color" icon-class="add" width="16" height="16" />
                        </span>
                    </el-button>
                </div>

                <el-table :data="tableData" style="width: 100%; cursor: pointer; margin-top: 10px; overflow: auto;"
                    @row-click="handleRowClick" :row-key="row => row.id" :expand-row-keys="expandedRows"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="40">
                    </el-table-column>
                    <el-table-column type="expand" width="20">
                        <template slot-scope="props">
                            <el-table :data="props.row.generateData" :show-header="false"
                                style="width: 100%; cursor: pointer; margin-top: 10px;">
                                <el-table-column type="selection" width="40">
                                </el-table-column>
                                <el-table-column label="生成想定" width="200">
                                    <template slot-scope="scope">
                                        <div style="display: flex; justify-content: space-between;align-items: center">
                                            {{ scope.row.name }}
                                            <svg-icon v-if="!scope.row.valid"
                                                style="color: var(--app-primary-base); margin-right: 20px;"
                                                icon-class="about-jtyun-cloud" width="16" height="16" />
                                        </div>

                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip label="基础想定" prop="name">
                        <template #default="{ row }">
                            <template v-if="row.invalidNum == 0">
                                {{ row.name }}
                            </template>
                            <template v-else>
                                <span role="img" class="appIcon">
                                    <svg-icon style="color: var(--app-primary-base);" icon-class="about-jtyun-cloud"
                                        width="16" height="16" />
                                </span>
                                {{ row.name }}
                            </template>
                        </template>

                    </el-table-column>

                    <el-table-column width="95" label="占比" prop="proportion">
                        <template slot-scope="props">
                            <el-input-number @blur="handleProportionBlur(props.row)" controls-position="right"
                                style="width: 100%;" :min="1" :max="9" v-model="props.row.proportion"
                                @click.native.stop></el-input-number>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 占比总计 -->
                <div
                    style="display: flex; justify-content: space-around; color: var(--app-primary-base); height: 42px; align-items: center;">
                    <div>占比总计</div>
                    <div>{{ totalProportion }}</div>
                </div>

            </div>

            <!-- 中间地图 -->
            <div class="e-b-middle">
                <div class="e-b-middle__button">
                    <el-tag class="button_item" @click="handleConfigClick('experimentFactorConfig')">
                        <svg-icon icon-class="folder" width="14" height="14" />
                        <div class="title-word">{{ $t("tool.experimentDesign.experimentFactorConfig") }}</div>
                    </el-tag>
                    <el-tag class="button_item" @click="handleConfigClick('scenarioFactorConfig')">
                        <svg-icon icon-class="folder" width="14" height="14" />
                        <div class="title-word">{{ $t("tool.experimentDesign.scenarioFactorConfig") }}</div>
                    </el-tag>
                    <el-tag class="button_item" @click="handleConfigClick('experimentBiasScript')">
                        <svg-icon icon-class="folder" width="14" height="14" />
                        <div class="title-word">{{ $t("tool.experimentDesign.experimentBiasScript") }}</div>
                    </el-tag>
                </div>
                <MarsMap :url="configUrl" @onload="onMapload">
                </MarsMap>
            </div>
        </div>
        <SelectScenarioDialog ref="selectScenarioDialog" :experimentId="experimentId" @refresh="getScenarioTableData"></SelectScenarioDialog>
        <ExperimentBiasScript ref="experimentBiasScript"></ExperimentBiasScript>
        <ExperimentFactorConfig ref="experimentFactorConfig"></ExperimentFactorConfig>
        <ScenarioFactorConfig ref="scenarioFactorConfig"></ScenarioFactorConfig>
        <ModelFactorConfig ref="modelFactorConfig"></ModelFactorConfig>
    </div>
</template>
<script>
import { getScenarioTableData } from "@/api/myspace/experiment-design-tool/experiment-design";
import MarsMap from "@/views/common-components/mars-map.vue";
import SelectScenarioDialog from "./components/select-scenario-dialog.vue";
import ExperimentBiasScript from "./components/experiment-bias-script.vue";
import ExperimentFactorConfig from "./components/experiment-factor-config.vue";
import ScenarioFactorConfig from "./components/scenario-factor-config.vue";
import ModelFactorConfig from "./components/model-factor-config.vue";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
let graphicLayer // 矢量图层对象
export default {
    name: "ScenarioBuild",
    data() {
        const basePathUrl = window.basePathUrl || ''
        return {
            configUrl: basePathUrl + '/config/map.json',
            queryContent: "",
            expandedRows: [],
            multipleSelection: [],
            tableData: [],
        };
    },
    props: {
        experimentId: {
            type: Number,
            default: 0,
        },
    },
    components: {
        MarsMap,
        SelectScenarioDialog,
        ExperimentBiasScript,
        ExperimentFactorConfig,
        ScenarioFactorConfig,
        ModelFactorConfig
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.scenarioEditTool.right_menuList,
            userId: (state) => state.user.id,
        }),
        filterNum() {
            return Object.values(this.filters).filter((item) => item).length - 1;
        },
        totalProportion() {
            if (!this.multipleSelection || this.multipleSelection.length === 0) {
                return 0;
            }
            return this.multipleSelection.reduce((total, item) => {
                const num = Number(item.proportion);
                return total + num;
            }, 0);
        }
    },
    created() {
        this.getScenarioTableData()
    },
    mounted() {
    },
    beforeDestroy() {
        graphicLayer.remove()
        graphicLayer = null
    },

    methods: {
        // 获取试验设计中的想定表格数据
        getScenarioTableData() { 
            getScenarioTableData().then(response => { 
                this.tableData = response.data
            })
        },
        // 地图构造完成回调
        onMapload(map) {
            let _this = this;
            graphicLayer = new mars3d.layer.GraphicLayer()
            
            // 在layer上绑定监听事件
            graphicLayer.on(mars3d.EventType.click, function (event) {
                console.log("监听layer，单击了矢量对象", event)
                _this.$refs["modelFactorConfig"].dialogVisible = true;
            })
            map.addLayer(graphicLayer);
            console.log("开始添加实体");
            // this.addEntity({ id: 1, nameChn: '实体1', sideId: 0 }, [132, 27, 10000], true)
            this.addDemoGraphic1()
            // this.addDemoGraphic2()
            // this.addDemoGraphic3()


        },
        addDemoGraphic1() {
            const graphic = new mars3d.graphic.ModelEntity({
                id:1,
                name: "警车",
                position: [116.346929, 30.861947, 401.34],
                style: {
                    url: "https://data.mars3d.cn/gltf/mars/jingche/jingche.gltf",
                    scale: 20,
                    minimumPixelSize: 50,
                    heading: 90,

                    distanceDisplayCondition: true,
                    distanceDisplayCondition_near: 0,
                    distanceDisplayCondition_far: 10000,
                    distanceDisplayPoint: {
                        // 当视角距离超过一定距离(distanceDisplayCondition_far定义的) 后显示为点对象的样式
                        color: "#00ff00",
                        pixelSize: 12
                    },

                    label: {
                        text: "我是原始的",
                        font_size: 18,
                        color: "#ffffff",
                        pixelOffsetY: -50,
                        distanceDisplayCondition: true,
                        distanceDisplayCondition_far: 10000,
                        distanceDisplayCondition_near: 0
                    }
                },
                attr: { remark: "示例1" }
            })
            graphicLayer.addGraphic(graphic)
        },
        addDemoGraphic2() {
            const graphic = new mars3d.graphic.DivBoderLabel({
                position: [116.460722, 31.140888, 781],
                style: {
                    text: "火星科技Mars3D平台",
                    font_size: 15,
                    font_family: "微软雅黑",
                    color: "#ccc",
                    boderColor: "#15d1f2"
                },
                attr: { remark: "示例6" }
            })

            // 测试修改className
            graphic.on(mars3d.EventType.load, function (e) {
                graphic.addClass("className1")
                graphic.addClass("className2")

                setTimeout(() => {
                    graphic.removeClass("className1")
                }, 9000)
            })
            graphicLayer.addGraphic(graphic)
        },
        addDemoGraphic3() {
            const graphic = new mars3d.graphic.DivGraphic({
                position: [116.228043, 30.882207],
                style: {
                    html: `<div class="marsTiltPanel marsTiltPanel-theme-green">
                                <div class="marsTiltPanel-wrap">
                                    <div class="area">
                                        <div class="arrow-lt"></div>
                                        <div class="b-t"></div>
                                        <div class="b-r"></div>
                                        <div class="b-b"></div>
                                        <div class="b-l"></div>
                                        <div class="arrow-rb"></div>
                                        <div class="label-wrap">
                                            <div class="title">大别山水厂</div>
                                            <div class="label-content">
                                                <div class="data-li">
                                                    <div class="data-label">实时流量：</div>
                                                    <div class="data-value"><span class="label-num">99</span><span class="label-unit">m³/s</span>
                                                    </div>
                                                </div>
                                                <div class="data-li">
                                                    <div class="data-label">水池液位：</div>
                                                    <div class="data-value"><span class="label-num">20.02</span><span class="label-unit">m</span>
                                                    </div>
                                                </div>
                                                <div class="data-li">
                                                    <div class="data-label">水泵状态：</div>
                                                    <div class="data-value"><span class="label-tag data-value-status-1" title="中间状态">1号</span><span
                                                            class="label-tag data-value-status-0" title="关闭状态">2号</span></div>
                                                </div>
                                                <div class="data-li">
                                                    <div class="data-label">出水阀门：</div>
                                                    <div class="data-value"><span class="label-tag data-value-status-1" title="中间状态">1号</span><span
                                                            class="label-tag data-value-status-2" title="打开状态">2号</span></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="b-t-l"></div>
                                    <div class="b-b-r"></div>
                                </div>
                                <div class="arrow" ></div>
                            </div>`,
                    horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 200000), // 按视距距离显示
                    // scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 200000, 0.2),
                    clampToGround: false
                },
                attr: { remark: "示例10" },
                // 可以传入自定义测试点样式
                // testPoint: {
                //   color: '#ff0000',
                //   pixelSize: 8,
                // },
                pointerEvents: false // false时不允许拾取和触发任意鼠标事件，但可以穿透div缩放地球
            })
            graphicLayer.addGraphic(graphic)

            graphic.testPoint = true // 打开测试点，与DIV点进行对比位置调整css
        },
        /** 添加实体 */
        addEntity(item, position, isVisible) {
            var pathEntity = new mars3d.graphic.PathEntity({
                id: item.id,
                position: position,
                show: isVisible,
                attr: item,
                maxCacheCount: 50,
                style: {
                    show: false,
                    resolution: 1,
                    leadTime: 0,
                    // trailTime: 10,
                    material: new Cesium.PolylineGlowMaterialProperty({
                        glowPower: 0.1,
                        taperPower: 0.5,
                        color: Cesium.Color.AQUA,
                    }),
                    width: 5,
                },
                model: {
                    uri: './FJ.glb',
                    minimumPixelSize: 50,
                    scale: 1000,
                    show: true,
                    runAnimations: true,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        0,
                        15000000
                    ), // 按视距距离显示
                },
                label: {
                    text: item.nameChn,
                    font_size: 15,
                    font_family: "黑体",
                    color: item.sideId == 0 ? "#FF5C5C" : "#84B5FF",
                    outline: false,
                    outlineColor: "#f1f1f1",
                    outlineWidth: 1,
                    background: true,
                    backgroundColor: "#000000",
                    backgroundOpacity: 0,
                    hasPixelOffset: true,
                    pixelOffsetY: -23,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        0,
                        8000000
                    ), // 按视距距离显示
                },
                point: {
                    color: item.sideId == 0 ? "#FF4242" : "#2979FF",
                    pixelSize: 10,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        15000000,
                        Number.MAX_VALUE
                    ), // 按视距距离显示
                },
            });
            graphicLayer.addGraphic(pathEntity);
        },
        handleProportionBlur(event, row) {
            if (event.proportion == undefined) {
                event.proportion = 1;
            }
        },

        handleQueryContent() {
            console.log("处理查询");
        },

        handleAddScenario(){
            this.$refs.selectScenarioDialog.init();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
        },

        handleRowClick(row) {
            console.log(row);
            const index = this.expandedRows.indexOf(row.id);
            if (index > -1) {
                // 如果已经展开，则关闭
                this.expandedRows.splice(index, 1);
            } else {
                // 否则展开
                this.expandedRows = [...this.expandedRows, row.id];
            }
        },
        nodeClick(node) {
            this.selectedNodeInfo = node;
            // 下面这三个赋值是用于点击[去编辑该数据模型]按钮时，让节点展开并选中
            // this.defaultExpandedKeys = Array.from(new Set([...this.defaultExpandedKeys, node.id]))
            // this.currentNodeKey = node.id;
            // this.$refs.scenarioBuildTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
        },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            experimentDataMoveTreeNode({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getSelfExperimentDataTree();
                }
            });
        },

        // 菜单点击
        handleMenuClick() {

        },


        // 处理节点配置、任务配置、规则配置的点击
        handleConfigClick(configName) {
            console.log(configName);
            if (configName == "experimentBiasScript") {
                this.$refs["experimentBiasScript"].drawer = true;
                return;
            }
            if (configName == "experimentFactorConfig") {
                this.$refs["experimentFactorConfig"].dialogVisible = true;
                return;
            }
            if (configName == "scenarioFactorConfig") {
                this.$refs["scenarioFactorConfig"].dialogVisible = true;
                return;
            }
        },
    }

};
</script>

<style lang="scss" scoped>
.experiment-build-container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;

    .experiment-build-container-top {
        height: 35px;
        display: flex;
        justify-content: flex-end;
        border-bottom: 1px solid var(--ui-border-color-base);

        .experiment-build-container-top_item {
            display: flex;
            margin-right: 20px;
            align-items: center;
            font-size: var(--ui-font-size-base);
            cursor: pointer;

            .title-word {
                margin-left: 5px;
            }
        }
    }

    .experiment-build-container-bottom {
        display: flex;
        height: calc(100% - 35px);
        padding: 0 0 0 10px;

        .e-b-left {
            width: 300px;
            height: 100%;
            display: flex;
            padding: 10px 10px 0 0;
            border-right: 1px solid var(--ui-border-color-split);

            ::v-deep .el-table__row {
                height: 42px;
            }

            ::v-deep .el-table-column--selection .cell {
                padding-left: 10px;
            }

            ::v-deep .el-table__expanded-cell {
                padding-left: 20px;
            }

            ::v-deep .el-table__body {
                width: 100% !important;
            }

        }

        .e-b-middle {
            width: calc(100% - 300px);
            min-width: 450px;
            height: 100%;

            // min-height: 868px;
            .e-b-middle__button {
                position: absolute;
                display: flex;
                top: 36px;
                right: 15px;
                z-index: 999;

                .button_item {
                    display: flex;
                    align-items: center;
                    font-size: var(--ui-font-size-base);
                    cursor: pointer;
                    margin-left: 4px;

                    .title-word {
                        margin-left: 5px;
                    }
                }
            }

        }


    }

}
</style>